import { NextRequest, NextResponse } from "next/server";
import { SqliteDatabase } from "@/lib/sqlite-database";

export async function POST(request: NextRequest) {
  try {
    console.log("开始清理设备119-130的位置参数...");
    
    const database = new SqliteDatabase();
    
    // 定义需要清理位置参数的设备ID范围
    const deviceIdsToClean = [];
    for (let i = 119; i <= 130; i++) {
      deviceIdsToClean.push(i);
    }
    
    let cleanedDevicesCount = 0;
    let deletedParametersCount = 0;
    const cleanedDevices = [];
    
    // 检查并清理每个设备的位置参数
    for (const deviceId of deviceIdsToClean) {
      // 获取设备信息
      const device = database.getDeviceById(deviceId);
      if (!device) {
        console.log(`设备 ID ${deviceId} 不存在`);
        continue;
      }
      
      // 检查是否有位置参数
      const positionParams = database.getPositionParametersByDeviceId(deviceId);
      if (positionParams.length > 0) {
        console.log(`设备 ${device.name} (ID: ${deviceId}) 有 ${positionParams.length} 个位置参数，准备删除...`);
        
        // 删除位置参数
        database.deletePositionParameters(device.device_id);
        
        cleanedDevicesCount++;
        deletedParametersCount += positionParams.length;
        cleanedDevices.push({
          id: deviceId,
          device_id: device.device_id,
          name: device.name,
          specialty: device.specialty,
          deletedCount: positionParams.length
        });
        
        console.log(`已删除设备 ${device.name} 的 ${positionParams.length} 个位置参数`);
      } else {
        console.log(`设备 ${device.name} (ID: ${deviceId}) 没有位置参数`);
      }
    }
    
    console.log(`清理完成！清理了 ${cleanedDevicesCount} 个设备的 ${deletedParametersCount} 个位置参数`);
    
    return NextResponse.json({
      success: true,
      message: `成功清理了 ${cleanedDevicesCount} 个设备的 ${deletedParametersCount} 个位置参数`,
      data: {
        targetDeviceRange: "119-130",
        cleanedDevicesCount,
        deletedParametersCount,
        cleanedDevices,
        summary: `设备119-130应该没有位置信息表参数，已清理完毕`
      }
    });
    
  } catch (error) {
    console.error("清理位置参数时出错:", error);
    return NextResponse.json(
      { 
        success: false, 
        message: "清理位置参数过程中发生错误",
        error: error instanceof Error ? error.message : "未知错误"
      },
      { status: 500 }
    );
  }
} 